<?php
namespace Admin\Controller;
use Admin\Controller\AdminController;

/**
 * 单位信息管理
 * Class LhspController
 * @package Admin\Controller
 */
class LhspController extends AdminController {

    /**
     * 系统管理 -> 系统管理 -> 建筑物信息维护 -> listview
     */
    public function index(){
        //获取搜索条件
        $this->assign("title", I("get.spdw"));
        $filter = $this->fn_GenerateFilter();
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();

        //分页信息
        $pageNum = intval(I("post.page"));
        $pageNum = $pageNum==0?1:$pageNum;
        $page = $this->fn_GetPageInfo($where, $pageNum);
        $this->assign("page", $page);

        //搜索出小区信息
        $limit = ($page['from']-1).",".$page['num'];
        $list = M("lhsp")->where($where)->order($order)->limit($limit)->select();
        for($i=0; $i<count($list); $i++){
            $list[$i]["offset"] = $page['from']-1+$i;
        }
        $this->assign("list", $list);

        //设置community信息
        $this->assign("area", $this->fn_GetAreaDict());

        //设置搜索条件
        $this->assign("filter", $filter);

        $this->display();
    }

    private function fn_GetAreaList(){
        return M("area")->where()->select();
    }

    private function fn_GetAreaDict(){
        $area = array();
        $list = M("area")->where()->select();
        for($i=0; $i<count($list); $i++){
            $area[$list[$i]["id"]] = $list[$i]["name"];
        }
        return $area;
    }

    /**
     * 建筑物信息维护 -> formview
     */
    public function detail(){
        //读取单位信息
        $dataId = I("get.id");
        $lhsp = M("lhsp")->where(array("id"=>$dataId))->find();
        $this->assign("lhsp", $lhsp);
        $this->assign("spdw", I("get.spdw"));

        if($lhsp['model']=="nianshen"){
            //当联合初审的状态不为accept时，则需要禁止审批功能
            $res = M($lhsp['model'])->where(array("no"=>$lhsp['no'], "state"=>"审核中"))->find();
            if($res){
                $this->assign("enableEdit", true);
            }
        }else{
            //当联合初审的状态不为accept时，则需要禁止审批功能
            $res = M($lhsp['model'])->where(array("no"=>$lhsp['no'], "state"=>"accept"))->find();
            if($res){
                $this->assign("enableEdit", true);
            }
        }

        //查询条件
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $pageInfo = $this->fn_GetPageInfo($where);

        //页面信息
        $offset = intval(I("get.offset"));
        $nearby = $this->fn_FindNearbyItems($where, $order, $offset);
        $page = array_merge($pageInfo, $nearby);
        $this->assign("page", $page);

        // 设置上下文信息
        $context = $this->fn_GenerateContext($page);
        $this->assign("context", $context);

        //设置area信息
        $options = $this->fn_GetAreaList();
        $this->assign("options", json_encode ($options));
        $area = $this->fn_GetAreaDict();
        $this->assign("area", $area);

        $this->display();
    }

    /**
     * 建筑物信息维护 -> 新增
     */
    public function add(){  //todo
        if(IS_POST){    //添加小区信息
            $data = array(
                "name" => I("post.name"),
                "community_id" => I("post.community_id"),
                "chanquan" => I("post.chanquan"),
                "floors" => I("post.floors"),
                "deadline" => I("post.deadline"),
                "remarks" => I("post.remarks"),
                "cuser" => session("username"),
                "ctime" => time()
            );
            $dataId = M("lhsp")->add($data);
            if($dataId){
                header("Location:/admin/lhsp/detail?id=".$dataId);
            }else{
                $this->error("系统错误，创建建筑物信息失败");
            }
        }

        //复制信息时处理流程
        if(I("get.id") && I("get.action"=="copy")){
            $house = M("lhsp")->where(array("id"=>I("get.id")))->find();
            $this->assign("lhsp", $house);
        }

        $this->display();
    }

    /**
     * AJAX方法，在listview中进行批量删除信息
     */
    public function ajax_del(){

        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $map["id"] = array("in", $dataIds);
        $res = M("lhsp")->where($map)->delete();
        if($res){
            $this->success("操作成功");
        }else{
            $this->error("系统错误");
        }
    }

    /**
     * AJAX方法，在formview中进行单条信息删除
     */
    public function ajax_del2(){
        //根据ID删除单位记录
        $id = I("post.id");
        $res = M("lhsp")->where(array("id" => $id))->delete();
        if(!$res){
            $this->error("系统错误");
        }

        //分页信息
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $total = $this->fn_GetTotalItems($where);
        if($total==0){
            $this->success(null);
        }

        //计算下一条记录的offset
        $offset = intval(I("post.offset"));
        $offset = ($offset>=$total-1)?0:$offset;

        //获取下一记录的信息
        $nextItem = $this->fn_GetInfoByOffset($offset, $where, $order);
        $this->success($nextItem["id"]); //返回下一条记录的ID
    }

    /**
     * AJAX方法，通过ID来修改审批状态。 并将状态同步到 保障业务申请表
     */
    public function ajax_UpdateInfoById(){
        $data = I("post.data");
        $data["spr"] = session("username");
        $data["sptime"] = time();
        $data["utime"] = time();
        $dataId = I("post.id");

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            $data['spyj'] = strtr($data['spyj'], [
                "{{chepai}}" => $data['chepai'],
                "{{estate_no}}" => $data["estate_no"],
                "{{estate_size}}" => $data["estate_size"],
                "{{estate_addr}}" => $data["estate_addr"],
                "{{estate_size2}}" => $data["estate_size2"],
                "{{dibaors}}" => $data["dibaors"],
                "{{tuixiu_t1}}" => $data["tuixiu_t1"],
                "{{tuixiu_t2}}" => $data["tuixiu_t2"],
                "{{tuixiu_j1}}" => $data["tuixiu_j1"],
                "{{tuixiu_j2}}" => $data["tuixiu_j2"],
                "{{marriage3}}" => $data["marriage3"],
                "{{name3}}" => $data["name3"],
                "{{idno3}}" => $data["idno3"],
            ]);
            $res = M("lhsp")->where(array("id"=>$dataId))->save($data);
            //$this->error(M("lhsp")->getLastSql());
            if(!$res){
                $this->error("更新审批状态异常2，请稍候再试");
            }

            //写入联合审批信息
            $lhsp = M("lhsp")->where(array("id"=>$dataId))->find();
            if($lhsp['spdw']=='婚姻登记处' && $lhsp['model']=='zlbt'){
                //第一步：清除非婚姻登记处的联合审批记录
                $this->fn_ClearLhspRecord($lhsp['no']);

                //第二步：写入其他单位的联合审批申请
                $zlbt = M("zlbt")->where(array("no"=>$lhsp['no']))->find();
                $lhspdw = parent::$spdw["租赁补贴"]["spdw"]; //增加3条联合审查记录
                foreach($lhspdw as $key){
                    $res = $this->fn_AddLhcsRecord($key, $lhsp, $zlbt);
                    //$this->error(M("lhsp")->getLastSql());
                    if(!$res){
                        $this->error("系统错误，联合审批信息写入失败");
                    }
                }
            }

            if($lhsp['spdw']=='婚姻登记处' && $lhsp['model']=='nianshen'){
                //第一步：清除非婚姻登记处的联合审批记录
                $this->fn_ClearLhspRecord($lhsp['no']);

                //第二步：写入其他单位的联合审批申请
                $nianshen = M("nianshen")->where(array("no"=>$lhsp['no']))->find();
                $type = $this->fn_GetApplyTypeByNo($nianshen['yw_no']);
                if($type=='廉租房'){
                    $apply = M("nianshen n")->field("l.*")
                        ->join(C('DB_PREFIX')."lzf l on l.no=n.yw_no", "LEFT")
                        ->where(array("l.no"=>$nianshen['yw_no']))->find();
                    $lhspdw = parent::$spdw[ $type ]["spdw"]; //增加3条联合审查记录
                    foreach($lhspdw as $key){
                        $res = $this->fn_AddLhcsRecord($key, $lhsp, $apply);
                        if(!$res){
                            $this->error("系统错误，联合审批信息1写入失败");
                        }
                    }
                }else if($type=='公租房'){
                    $apply = M("nianshen n")->field("g.*")
                        ->join(C('DB_PREFIX')."gzf g on g.no=n.yw_no", "LEFT")
                        ->where(array("g.no"=>$nianshen['yw_no']))->find();
                    $lhspdw = parent::$spdw[ $type ]["spdw"][ $apply["applier_type"] ];
                    foreach($lhspdw as $key){
                        if($key=='人社局企业保险股' && $apply['work_state']=='机关事业单位'){
                            continue; //机关事业单位不需要 人社局企业保险股审批
                        }
                        if($key=='人社局机关事业保险股' && $apply['work_state']!='机关事业单位'){
                            continue; //非机关事业单位不需要 人社局机关事业保险股审
                        }
                        $res = $this->fn_AddLhcsRecord($key, $lhsp, $apply);
                        //$this->error(M("lhsp")->getLastSql());
                        if(!$res){
                            $this->error("系统错误，联合审批信息2写入失败");
                        }
                    }
                }
            }

            $res = $this->fn_UpdateLhspState($lhsp["no"], $lhsp["model"]);
            if(!$res){
                $this->error("审批失败，无法同步审批状态");
            }

            $trans->commit();   // 提交事务
            $this->success("操作成功");

        }catch (Exception $e){
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    public function fn_ClearLhspRecord($nsNo){
        return M("lhsp")->where(array("no"=>$nsNo, "spdw"=>array("neq","婚姻登记处")))->delete();
    }

    public function fn_GetApplyTypeByNo($no){
        $prefix = substr($no, 0, 1);
        if($prefix=="L"){
            return '廉租房';
        }else if($prefix=="G"){
            return '公租房';
        }else if($prefix=="Z"){
            return '租赁补贴';
        }
        return null;
    }

    protected function fn_AddLhcsRecord($spdw, $lhsp, $apply){
        $lhsp = array(
            "spdw" => $spdw,
            "type" => $lhsp['type'],
            "model" => $lhsp['model'],
            "no" => $lhsp["no"],
            "name" => $apply["name"],
            "marriage" => $lhsp["marriage3"],
            "gender" => $apply["gender"],
            "idno" => $apply["idno"],
            "area_id" => $apply["area_id"],
            "phone" => $apply["phone"],
            "dibaork" => $apply["dibaork"],
            "dibaohm" => $apply["dibaohm"],
            "income" => $apply["income"],
            "estate" => $apply["estate"],
            "name2" => $lhsp['name3'], //婚姻情况
            "idno2" => $lhsp['idno3'], //婚姻情况
            "gender2" => $this->fn_GetGenderByIdno($lhsp['idno3']),
            "sqtime" => time(),
        );
        return M("lhsp")->add($lhsp);
    }

    public function fn_GetGenderByIdno($idno){
        if(strlen($idno)!=18){
            return null;
        }
        $tag = substr($idno, 16, 1);
        if($tag%2=='1'){
            return "男";
        }else if($tag%2==0){
            return "女";
        }
    }

    public function fn_UpdateLhspState($no, $model){
        $where = array("no"=>$no, "spzt"=>"未审批");
        $res = M("lhsp")->where($where)->find();
        if(!$res){
            //更新 保障房申请 联合审批状态为：已完成联合审批
            $data = array("lhsp" => 1, "utime"=>time());
            return M($model)->where(array("no"=>$no))->save($data);
        }
        return true;
    }

    /**
     *  辅助方法，通过$_POST的值来生成where查询条件
     */
    private function fn_GenerateWhereClause(){
        $where = array("spdw"=>I("get.spdw"));
        //对于角色为社区审批员的用户过行智能过滤
        if(self::$u['area_id']){ //如果用户设置了审批范围，则只能审批本辖区内的申请；
            $where['area_id'] = self::$u['area_id'];
        }
        if(I("request.value")) {
            $where[I("request.field")] = array("like", "%" . I("request.value") . "%");
        }
        return $where;
    }

    /**
     *  辅助方法，通过$_POST的值来生成order by子句
     */
    private function fn_GenerateOrderBy(){
        $order = "id desc";
        if(I("request.order_field") && I("request.order_sort")){
            $order = I("request.order_field") . " " . I("request.order_sort");
        }
        return $order;
    }

    /**
     *  辅助方法，通过$_POST的值来生成Filter (listview)
     */
    private function fn_GenerateFilter(){
        if(IS_POST){
            return array(
                "page" => I("post.page"),
                "field" => I("post.field"),
                "value" => I("post.value"),
                "spdw" => I("post.spdw"),
                "order_field" => I("post.order_field"),
                "order_sort" => I("post.order_sort"),
            );
        }
        return array(
            "page" => 1,
            "spdw" => I("get.spdw"),
            "order_field" => "id",
            "order_sort" => "desc",
        );
    }

    /**
     * 辅助方法，通过$_POST的值来生成Context (formvier)
     * @return array
     */
    private function fn_GenerateContext($page){
        return array(
            "id" => I("request.id"),
            "field" => I("request.field"),
            "value" => I("request.value"),
            "spdw" => I("request.spdw"),
            "order_field" => I("request.order_field"),
            "order_sort" => I("request.order_sort"),
            "page" => I("request.page"),
            "offset" => I("request.offset"),
            "index" => I("get.offset")-($page["curPage"]-1)*$page["num"]+1
        );
    }

    /**
     * 辅助方法，通过where,order,offset来查询信息
     * @param $offset
     * @param $where
     * @param $order
     * @return mixed
     */
    private function fn_GetInfoByOffset($offset, $where, $order){
        $limit = $offset.",1";
        $res =  M("lhsp")->field("id,name")->where($where)->order($order)->limit($limit)->select();
        if($res){
            return $res[0];
        }
        return array();
    }

    /**
     * 辅助方法，通过where, curpage, num来生成分页信息
     * @param $where
     * @param int $curPage
     * @param int $num
     * @return array
     */
    private function fn_GetPageInfo($where, $curPage=1, $num=5){
        $total = M("lhsp")->where($where)->count();
        $totalPage = ceil($total/$num);
        $nextPage = $curPage==$totalPage?1:($curPage+1);
        $prevPage = $curPage==1?$totalPage:($curPage-1);
        $to = $curPage*$num;
        $res = array(
            "total" => $total,
            "num" => $num,
            "from" => (($curPage-1)*$num+1),
            "to" => $to>$total?$total:$to,
            "curPage" => $curPage,
            "nextPage" => $nextPage,
            "prevPage" => $prevPage
        );
        return $res;
    }

    /**
     * 辅助方法，通过where来统计总的信息数量
     * @param array $where
     * @return mixed
     */
    public function fn_GetTotalItems($where=array()){
        return M("lhsp")->where($where)->count();
    }

    /**
     * 辅助方法，通过where, order, offset查询相邻两条数据
     * @param $where
     * @param $offset
     */
    public function fn_FindNearbyItems($where, $order, $offset){
        $total = M("lhsp")->where($where)->count();
        $prevOffset = $offset>0?$offset-1:$total-1;
        $nextOffset = $offset>=$total-1?0:$offset+1;
        $prevItem = $this->fn_GetInfoByOffset($prevOffset, $where, $order);
        $nextItem = $this->fn_GetInfoByOffset($nextOffset, $where, $order);
        return array(
            "prev" => array("id"=>$prevItem["id"],"offset"=>$prevOffset),
            "next" => array("id"=>$nextItem["id"],"offset"=>$nextOffset),
        );
    }

}